package com.tofine.smarthome.ui;

import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.activeandroid.query.Select;
import com.google.gson.Gson;
import com.roughike.bottombar.BottomBar;
import com.roughike.bottombar.OnMenuTabClickListener;
import com.tofine.smarthome.Constants;
import com.tofine.smarthome.R;
import com.tofine.smarthome.base.BaseActivity;
import com.tofine.smarthome.fragment.DeviceFragment;
import com.tofine.smarthome.fragment.FavoriteFragment;
import com.tofine.smarthome.fragment.SceneFragment;
import com.tofine.smarthome.fragment.SettingsFragment;
import com.tofine.smarthome.model.Device;
import com.tofine.smarthome.receiver.DeviceCommandReceiver;
import com.tofine.smarthome.rest.model.Command;
import com.tofine.smarthome.util.CommandUtils;

import butterknife.Bind;
import cn.bmob.push.BmobPush;
import cn.bmob.push.PushConstants;
import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobInstallation;

/**
 * @author ddMax
 * @since 2016/4/25
 * 说明：App主Activity
 */
public class MainActivity extends BaseActivity {
    public static final String TAG = MainActivity.class.getSimpleName();

    @Bind(R.id.main_container) FrameLayout mContainer;
    private BottomBar mBottomBar;

    private DeviceCommandReceiver mReceiver;

    private Fragment[] fragments = {
            DeviceFragment.newInstance(),
            SceneFragment.newInstance(),
            FavoriteFragment.newInstance(),
            SettingsFragment.newInstance()
    };

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected boolean hasActionBar() {
        return false;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        // 初始化推送
        Bmob.initialize(this, Constants.BMOB_APPKEY);
        BmobInstallation.getCurrentInstallation(this).save();
        BmobPush.startWork(this);

        setUpBottomBar(savedInstanceState);
    }

    @Override
    public void initData() {

    }

    @Override
    public void initView() {
//        initFragment();
        // 注册Receiver
        initCommandReceiver();
    }

    /**
     * 初始化设备命令接收器
     */
    private void initCommandReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction("cn.bmob.push.action.MESSAGE");
        mReceiver = new DeviceCommandReceiver();
        mReceiver.setOnReceivedCommandListener(new DeviceCommandReceiver.CommandListener() {
            @Override
            public void onCommandReceived(Command command) {
                Device device = new Select().from(Device.class).where("_id = " + command.getId()).executeSingle();
                boolean result = CommandUtils.execute(device, command.getCommand());
                String message = result ?
                        "设备: " + device.name + "已打开"
                        : "设备: " + device.name + "已关闭";
                // 更新DeviceFragment界面
                ((DeviceFragment) fragments[0]).updateSegmentCheckedStatus();
                Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
            }
        });
        registerReceiver(mReceiver, filter);
    }

    private void initFragment() {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        for (Fragment fragment : fragments) {
            if (!fragment.isAdded()) {
                transaction.add(R.id.main_container, fragment);
            }
        }
        transaction.replace(R.id.main_container, fragments[0]);
        transaction.commit();
    }

    private void setUpBottomBar(Bundle savedInstanceState) {
        mBottomBar = BottomBar.attach(this, savedInstanceState);
        mBottomBar.useFixedMode();
        mBottomBar.setItemsFromMenu(R.menu.bottombar_menu, new OnMenuTabClickListener() {
            @Override
            public void onMenuTabSelected(@IdRes int menuItemId) {
                switchFragment(menuItemId, false);
            }

            @Override
            public void onMenuTabReSelected(@IdRes int menuItemId) {
                switchFragment(menuItemId, true);
            }
        });
    }

    /**
     * 当底部栏选项改变时，对应页面的切换
     * @param menuItemId 标签菜单id
     * @param isReselection 是否为当前已选中的项
     */
    private void switchFragment(int menuItemId, boolean isReselection) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        switch (menuItemId) {
            case R.id.bottomBarItemDevices:
                transaction.replace(R.id.main_container, fragments[0]);
                break;
            case R.id.bottomBarItemScenes:
                transaction.replace(R.id.main_container, fragments[1]);
                break;
            case R.id.bottomBarItemFavorite:
                transaction.replace(R.id.main_container, fragments[2]);
                break;
            case R.id.bottomBarItemSettings:
                transaction.replace(R.id.main_container, fragments[3]);
                break;
        }
        transaction.commit();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        mBottomBar.onSaveInstanceState(outState);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        ((DeviceFragment) fragments[0]).updateSegmentCheckedStatus();
        Gson gson = new Gson();
        Command command = gson.fromJson(intent.getStringExtra(PushConstants.EXTRA_PUSH_MESSAGE_STRING), Command.class);
        Log.d(TAG, command.toString());
        super.onNewIntent(intent);
    }

    @Override
    protected void onDestroy() {
        if (mReceiver != null) {
            unregisterReceiver(mReceiver);
        }
        super.onDestroy();
    }
}
